package com.happy.service.main.bl;

import com.alibaba.fastjson.JSONObject;
import com.happy.core.dto.UserDTO;
import com.happy.core.dto.WeiXinDTO;
import com.happy.core.enums.UserTypeEnum;
import com.happy.core.util.AssertUtils;
import com.happy.core.util.WeiXinUtil;
import com.happy.service.main.dao.UserMapper;
import com.happy.service.main.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: happy-shopping-op
 * @description: 微信业务逻辑层
 * @author: taoxinhuan
 * @create: 2020-04-02 20:51
 **/
@Service
public class WeiXinBL {
    @Value("${wexin.appId}")
    private String appId;

    @Value("${wexin.secret}")
    private String secret;

    @Value("${wexin.code2Session_url}")
    private String code2Session_url;

    @Autowired
    private UserBL userBL;
    @Autowired
    private UserMapper userMapper;

    @Transactional
    public void login(WeiXinDTO dto) {
        String jsCode = dto.getJsCode();
        RestTemplate restTemplate = new RestTemplate();
        Map map = new HashMap();
        map.put("appId", appId);
        map.put("secret", secret);
        map.put("js_code", jsCode);
        map.put("grant_type", "authorization_code");
        String url = WeiXinUtil.handUrl(code2Session_url, map);
        String forEntity = restTemplate.getForObject(url, String.class);
        System.out.println(forEntity);
        JSONObject obj = (JSONObject)JSONObject.parse(forEntity);
        String openid = obj.getString("openid");
        String errmsg = obj.getString("errmsg");
        AssertUtils.notNull(openid,errmsg);
        UserDTO userDTO = dto.getUserDTO();
        userDTO.setUserOpenId(openid);
        User user = userMapper.getUserByOpenId(openid);
        if (user==null){
            userDTO.setType(UserTypeEnum.COMMEN_USER.getKey());
            userBL.insertUser(userDTO,1L);
        }else{
            userBL.updateUser(userDTO,1L);
        }

    }

}
